﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Xml.Linq;
using OpenLS.Core.Serialization;
using OpenLS.Spreadsheet.Serialization;

namespace OpenLS.Spreadsheet
{
    partial class Workbook
    {
#if NET40
        private readonly List<XDocument> _customXml = new List<XDocument>();
        public List<XDocument> CustomXmlDocuments
        {
            get { return _customXml; }
        }

        private void WriteCustomXml(WriteContext context)
        {
            foreach (var customXml in CustomXmlDocuments)
            {
                var relatedContext = context.CreateRelatedContext("", "",
                                                                  context.GetAvailableUri("/customXml/item{0}.xml"),
                                                                  SpreadsheetConstants.CustomXmlRelationship,
                                                                  "application/xml");
                {
                    customXml.WriteTo(relatedContext.Writer);
                    relatedContext.Writer.Close();
                }
            }
        }

        private void ReadCustomXml(ReadContext context)
        {
            foreach (var c in context.GetRelatedContexts(SpreadsheetConstants.CustomXmlRelationship, string.Empty))
            {
                using (var stream = c.Part.GetStream())
                {
                    CustomXmlDocuments.Add(XDocument.Load(c.Part.GetStream()));
                }
            }
        }
#endif
    }
}